import { Controller, Inject, Post, Body, Get, Query } from '@midwayjs/core';
import { ApiTags, ApiOperation, ApiResponse, ApiBody, ApiQuery } from '@midwayjs/swagger';
import { BusinessType, Log } from '../decorator/log.decorator';
import { AllocateService } from '@service/allocate.service';
import { ExecuteAllocateDto, ExportAllocateDto, ManualAllocateDto, GetAvailableTeachersDto, CancelAllocateDto } from '@dto/allocate.dto';

@ApiTags('师生匹配分配')
@Controller('system/allocate')
export class AllocateController {
  @Inject()
  allocateService: AllocateService;

  /**
   * 执行师生双向匹配
   */
  @ApiOperation({
    summary: '执行师生双向匹配',
    description: '基于志愿得分进行师生双向匹配，剩余队伍随机分配',
  })
  @ApiBody({ type: ExecuteAllocateDto, description: '分配请求参数' })
  @ApiResponse({ status: 200, description: '匹配成功' })
  @Log({ title: '师生匹配-执行分配', businessType: BusinessType.OTHER })
  @Post('/execute')
  async executeMatch(@Body() body: ExecuteAllocateDto) {
    return await this.allocateService.executeMatch(body.groupId);
  }

  /**
   * 管理员手动分配
   */
  @ApiOperation({
    summary: '管理员手动分配',
    description: '管理员手动将队伍分配给教师（sort=0标识，不会被自动分配覆盖）',
  })
  @ApiBody({ type: ManualAllocateDto, description: '手动分配请求参数' })
  @ApiResponse({ status: 200, description: '分配成功' })
  @Log({ title: '师生匹配-手动分配', businessType: BusinessType.OTHER })
  @Post('/manual')
  async manualAllocate(@Body() body: ManualAllocateDto) {
    return await this.allocateService.manualAllocate(body.teamId, body.teacherId);
  }

  /**
   * 取消选择
   */
  @ApiOperation({
    summary: '取消选择',
    description: '取消队伍和教师之间的匹配关系',
  })
  @ApiBody({ type: CancelAllocateDto, description: '取消选择请求参数' })
  @ApiResponse({ status: 200, description: '取消成功' })
  @Log({ title: '师生匹配-取消选择', businessType: BusinessType.OTHER })
  @Post('/cancel')
  async cancelAllocate(@Body() body: CancelAllocateDto) {
    return await this.allocateService.cancelAllocate(body.teamId, body.teacherId);
  }

  /**
   * 获取空闲教师列表
   */
  @ApiOperation({
    summary: '获取空闲教师列表',
    description: '获取指定分组下还有空闲位置的教师列表，按剩余名额降序排序',
  })
  @ApiQuery({ name: 'groupId', description: '分组ID', type: 'number' })
  @ApiResponse({ status: 200, description: '查询成功' })
  @Log({ title: '师生匹配-查询空闲教师', businessType: BusinessType.LIST })
  @Get('/available-teachers')
  async getAvailableTeachers(@Query() query: GetAvailableTeachersDto) {
    return await this.allocateService.getAvailableTeachers(query.groupId);
  }

  /**
   * 导出分配结果
   */
  @ApiOperation({
    summary: '导出分配结果',
    description: '导出指定分组的师生分配结果为 Excel 文件',
  })
  @ApiBody({ type: ExportAllocateDto, description: '导出请求参数' })
  @ApiResponse({ status: 200, description: '导出成功' })
  @Log({ title: '师生匹配-导出结果', businessType: BusinessType.EXPORT })
  @Post('/export')
  async export(@Body() body: ExportAllocateDto) {
    return await this.allocateService.export(body.groupId);
  }
}
